package com.learning.controller;

import com.learning.service.impl.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author wangyunyun
 */
@RestController
@RequestMapping("/async")
public class asyncController {

	@Autowired
	private AsyncService asyncService;

	@GetMapping("/run-task")
	public String runTask() throws InterruptedException {
		for (int i = 1; i <= 50; i++) {
			asyncService.processTask("TASK-" + i);
		}
		return "5个异步任务已触发";
	}

	@GetMapping("/future-task")
	public String futureTask() throws InterruptedException, ExecutionException {
		Future<String> future = asyncService.processWithResult("hello");
		// 阻塞获取结果（实际项目中应避免在Controller中阻塞）
		return future.get();
	}

	@GetMapping("/completable-future")
	public String completableFuture() throws Exception {
		CompletableFuture<Integer> future1 = asyncService.calculateAsync(5);
		CompletableFuture<Integer> future2 = asyncService.calculateAsync(10);

		// 组合多个异步任务
		CompletableFuture.allOf(future1, future2).join();

		return String.format("计算结果: %d + %d = %d",
				future1.get(), future2.get(),
				future1.get() + future2.get());
	}

	@GetMapping("/test-exception")
	public String testException() {
		asyncService.processWithException();
		return "异常测试已触发";
	}

}
